<?php

namespace App\Models\Api;

class HuanXin
{
    private $org_name = '';
    private $app_name = '';
    private $client_id = '';
    private $client_secret = '';
    private $url = '';

    public function __construct()
    {
        $this->org_name = '1126170714115618';
        $this->app_name = '1wyuncmstest';
        $this->client_id = 'YXA6Y0vjwGhbEeeQCA1x1fY2Pg';
        $this->client_secret = 'YXA6iRxlvuANffS40t9ES2NNJRPPp8Y';
        $this->url = 'https://a1.easemob.com/' . $this->org_name . '/' . $this->app_name . '/';
    }

    /** 为单个用户注册环信账号
     * @param $username
     * @return mixed
     */
    public function register($username)
    {
        $url = $this->url . 'users';
        $data = [
            'username' => $username,
            'password' => $username,
        ];
        return $this->curl($url, $data);
    }

    /** 获取环信token,true则不读取缓存
     * @param bool|false $new
     * @return mixed
     */
    private function getToken($new = false)
    {
        $key = 'huanxin_access_token';
        if (\Cache::has($key) && !$new) {//不需要更新,而且缓存在
            return \Cache::get($key);
        }

        $token = '';
        $url = $this->url . 'token';
        $data = [
            'grant_type' => 'client_credentials',
            'client_id' => $this->client_id,
            'client_secret' => $this->client_secret
        ];
        $rs = $this->curl($url, $data, 'POST', false);

        if ($rs !== false) {
            $token = $rs['access_token'];
            \Cache::forever($key, $token);
        }

        return $token;
    }

    /** 封装curl
     * @param $url
     * @param $data
     * @param bool|false $header
     * @param string $method
     * @return mixed
     */
    private function curl($url, $data, $method = 'POST', $header = true)
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($header) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $this->getToken()
            ]);
        }
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if (!empty($data)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $ret = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        if ($httpCode == 401) {//token失效
            $this->getToken(true);//更新token
            return $this->curl($url, $data, $method, $header);//重新请求
        } elseif ($httpCode == 200) {
            return json_decode($ret, true);
        }
        return false;
    }
}